#include "sg4c.h"
#include <math.h>

#define PI 3.14159

float amp, tau, freq;

sg_font_t font;

void setup(){
    amp = sgHeight()/2;
    tau = 0;
    freq = 2;
    font = sgCreateFont("dialog", 12);

}

void draw(){
    int x;

    sgFill( sgGray(0xff) );
    sgNoStroke();
    sgRect(0, 0, sgWidth(), sgHeight() );

    sgStrokeWeight(2);

    float rad = tau;
    int px = 0;
    int py = amp*sinf(rad*freq) + sgHeight()/2;
    for( x=1; x<sgWidth(); ++x){
        rad = (float)x/sgWidth()*PI*2 + tau;
        int cx = x;
        int cy = amp*sinf(rad*freq) + sgHeight()/2;
        sgLine( px, py, cx, cy );
        px = cx;
        py = cy;
    }

    sgFill( sgHexRGB(0x6666aa) );
    sgFont( font );

    sgText( "Move mouse to change tau and amp", 10, font.height   );
    sgText( "Drag mouse to change frequency", 10, font.height*2 );
}


//events
void mouseMoved(){
    float ypos = (float)sgMouse().y / sgHeight() * 2 - 1;
    amp = ypos * sgHeight()/2;

    float xpos = (float)sgMouse().x / sgWidth();
    tau = PI * 2 * xpos;

    sgRedraw();
}

void mousePressed(){
    //A mouse button is pressed
}

void mouseReleased(){
    //A mouse button is released
}

void mouseClicked(){
    //A mouse button is pressed and released
}

void mouseDragged(){
    int delta = sgMouse().x - sgMousePrevious().x;

    freq += delta * 0.05f;
    sgRedraw();
}

void mouseEntered(){
    //The mouse pointer enters the display frame
}

void mouseExited(){
    //The mouse pointer leaves the display frame
}

void keyReleased(){
    //A key is released
}

void keyPressed(){
    //A key is pressed
}

void keyTyped(){
    //A key is pressed and then released
}

int main(){
    sg_config_t config;
    sgInitConfig( &config );

    config.screen.width = 600;  //set the horizontal resolution of the frame
    config.screen.height = 400; //set the vertical resolution of the frame
    config.framerate = 0;      //set to 0 for backend driven

    config.smooth = 1; // uncomment this line to enable smoothing

    //------------------------------------------------------------------
    //DO NOT MODIFY CODE BELOW

    //setup callbacks
    config.setup = setup;
    config.draw = draw;

    config.mousePressed = mousePressed;
    config.mouseReleased = mouseReleased;
    config.mouseMoved = mouseMoved;
    config.mouseEntered = mouseEntered;
    config.mouseExited = mouseExited;
    config.mouseClicked = mouseClicked;
    config.mouseDragged = mouseDragged;

    config.keyReleased = keyReleased;
    config.keyPressed = keyPressed;
    config.keyTyped = keyTyped;

    //initilize the system
    sgSetup(&config);

    //run forever
    return sgRunForever();
}
